package main

import (
	"context"
	"fmt"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
	"web_app/dao/mysql"
	"web_app/dao/redis"
	"web_app/logger"
	"web_app/routes"
	"web_app/settings"
)

func main() {
	// 加载配置
	if err := settings.Init(); err != nil {
		return
	}

	// 初始化日志
	if err := logger.Init(); err != nil {
		return
	}

	defer zap.L().Sync()

	// 初始化mysql
	if err := mysql.Init(); err != nil {
		return
	}
	defer mysql.Close()

	// 初始化redis
	err := redis.Init()
	if err != nil {
		return
	}
	defer redis.Close()

	// 注册路由
	r := routes.Setup()
	// 启动服务
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%s", viper.GetString("app.port")),
		Handler: r,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			zap.L().Fatal("ListenAndServe:%s\n", zap.Error(err))
		}
	}()

	shutdown(srv)
}

func shutdown(srv *http.Server) {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	zap.L().Info("Shutdown server...")
	timeout, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()
	if err := srv.Shutdown(timeout); err != nil {
		zap.L().Info("Shutdown", zap.Error(err))
	}

	zap.L().Info("server exit")
}
